using Cysharp.Threading.Tasks;
using GameLogic.GameLogic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;

namespace GameLogic
{
    [Window(UILayer.UI)]
    public class MenuUI : UIWindow
    {
        public Button startNewGameBtn;
        public Button loadSaveBtn;
        public Button settingBtn;

        private CancellationTokenSource _cts;
		private CancellationTokenSource _destroyCts;

        protected override void ScriptGenerator()
        {
            startNewGameBtn = FindChild("MenuPanel/GameBtnGroup/StartNewGameBtn").gameObject.GetComponent<Button>();
            loadSaveBtn = FindChild("MenuPanel/GameBtnGroup/LoadSaveBtn").gameObject.GetComponent<Button>();
            settingBtn = FindChild("MenuPanel/GameBtnGroup/SettingBtn").gameObject.GetComponent<Button>();
            startNewGameBtn.onClick.AddListener(OnClickStartNewGameBtn);
            loadSaveBtn.onClick.AddListener(OnLoadSaveBtn);
			settingBtn.onClick.AddListener(OnSettingBtn);
        }

        private void OnClickStartNewGameBtn()
        {
            if (_cts != null) return; // 防重复点击
            _cts = new CancellationTokenSource();
            RunStartNewGame(_cts.Token).Forget();
        }

        private async UniTaskVoid RunStartNewGame(CancellationToken token)
        {
			// 窗口销毁自动取消（自管理的 CTS，兼容无 GetCancellationTokenOnDestroy 的环境）
			var destroyToken = _destroyCts != null ? _destroyCts.Token : CancellationToken.None;
			using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, destroyToken);

			// 缓存引用，避免 this 被销毁后访问字段
			var btn = startNewGameBtn;

			try
            {
				if (btn != null) btn.interactable = false;
				await GameFlow.StartNewGameAsync(linked.Token);
			}
			catch (OperationCanceledException)
			{
				// 窗口销毁或外部取消，忽略
            }
            catch (Exception ex)
            {
                Debug.LogError($"StartNewGame 出错: {ex}");
            }
            finally
            {
				if (this != null && btn != null) btn.interactable = true;
                _cts?.Dispose();
                _cts = null;
            }
        }

        private void OnLoadSaveBtn()
        {

        }

        private void OnSettingBtn()
        {

        }

        private static async UniTaskVoid StartBattleRoom()
        {
            try
            {
                await GameModule.Scene.LoadSceneAsync("FarmScene");
                UIModule.Instance.CloseUI<MenuUI>();
                await UIModule.Instance.ShowUIAsyncAwait<MainUI>();
            }
            catch (Exception ex)
            {
                Debug.LogError($"StartBattleRoom 执行出错: {ex.Message}");
            }
        }

		protected override void OnDestroy()
		{
			_cts?.Cancel();
			_cts?.Dispose();
			_cts = null;

			_destroyCts?.Cancel();
			_destroyCts?.Dispose();
			_destroyCts = null;
			base.OnDestroy();
		}
    }
}
